package com.sna.snaapplication.config;


import com.sna.snaapplication.service.core.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 返回AuthenticationManager对象
    @Bean
    AuthenticationManager authenticationManager(){
        DaoAuthenticationProvider dao=new DaoAuthenticationProvider();
        dao.setUserDetailsService(myUserDetailsService); //这里需要一个实现用户详情服务类，接着创建该类
        dao.setPasswordEncoder(bCryptPasswordEncoder());
        ProviderManager providerManager=new ProviderManager(dao);
        return providerManager;
    }

    // 返回创建密码加密器：BCryptPasswordEncoder
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    MyUserDetailsService myUserDetailsService;


    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> {
            // 允许所有用户访问登录相关路径
            auth.requestMatchers("/login/**").permitAll()
                    .requestMatchers("/register/**").permitAll()
                    .requestMatchers("/j2000-orbit-czml2/**").permitAll()
                    .requestMatchers("/api/captcha/**").permitAll()
                    // 用户管理页面只能管理员访问
                    .requestMatchers("/admin/UserManage").hasRole("admin")
                    // 其他所有路径允许所有已认证用户访问
                    .anyRequest().authenticated();
        });

        // 禁用 CSRF 保护（根据实际需求决定是否禁用）
        http.csrf(c -> c.disable());

        // 返回构建的 SecurityFilterChain 对象
        return http.build();
    }

}

